package com.hmeter.mongodb;

import java.net.UnknownHostException;
import java.util.List;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.MongoException;

public class MongoDbReadSamplerUtility {

	private MongoDbUtility mongoDbUtility = null;
	
	public MongoDbReadSamplerUtility(String host, int port, String dbName, String collectionName) throws UnknownHostException
	{
		mongoDbUtility = new MongoDbUtility(host, port, dbName, collectionName);
	}
	
	public MongoDbUtility getMongoDbUtility()
	{
		return mongoDbUtility;
	}
	
	public String readAllDocumentsFromCollection()
	{
		StringBuilder content = new StringBuilder();
		BasicDBObject query = new BasicDBObject();
		DBCursor cursor = mongoDbUtility.getMongoDbCollection().find(query);
		
		while (cursor.hasNext())
		{
			content.append(cursor.next() + "\n");
		}	
		return content.toString();
	}
	
	public String readDocumentsFromCollectionByClause(List<BasicDBObject> objects, String operator)
	{
		StringBuilder content = new StringBuilder();
		BasicDBObject query = new BasicDBObject();
		query.put(operator, objects);
		
		try 
		{ 
			DBCursor cursor = mongoDbUtility.getMongoDbCollection().find(query);
			while (cursor.hasNext())
			{
				content.append(cursor.next() + "\n");
			}
		} 
		catch (MongoException ex) 
		{
			System.out.println(ex.getMessage());
		}		
		return content.toString();
	}
}
